package com.zcsy.manage.web.system;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.ehcache.CacheConstants;
import com.zcsy.commons.ehcache.CacheUtils;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.DictVo;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.weixin.StringUtil;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;

/**
 * @Title: DictController.java
 * @Package： com.zcsy.manage.web.system 
 * @Description: 数据字典控制层
 *
 * @author caiyinli 13277030520@qq.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年1月25日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/dict")
public class DictController {
    
    private static final int NEW_ID   =  0;  //新增字典默认id
	
    @Autowired
    private IDictService dictService;

    /**
     * @Description 根据搜索条件返回数据字典列表<br>
     * 
     * @param model
     * @param pNo 当前页码
     * @param searchKey 搜索关键词
     * @param req 用户请求
     * @return 返回搜索列表
     * @author caiyinli 13277030520@qq.com
     * @date 2016年1月21日
     * @see 
     */
    @RequestMapping(value="dictList" , method = RequestMethod.GET)
    public String  getDictList(Model model,Integer pNo,Integer pSize, String searchKey, HttpServletRequest req) {
	    if(pNo == null){
            pNo = Constants.PAGE_NO;
        }

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
    	PageHelper.startPage(pNo, pageSize);
    	
        Dict dict = new Dict();
        if(StringUtils.isNotEmpty(searchKey)){
        	dict.setDescription(searchKey);
        }
        List<Dict> dictList = dictService.queryDict(dict);
        PageInfo<Dict> dicts = new PageInfo<Dict>(dictList);
		model.addAttribute("dicts", dicts);
		model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
		model.addAttribute("searchKey", searchKey);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

        return "system/dict/dictList";
    }
    

	/**
	 * @Description 新增或编辑字典时的保存方法<br>
	 * 
	 * @param dictVos 统一类型字典数据的集合
	 * @param descript 字典描述
	 * @param type 字典类型（只能为英文）
	 * @param dictid 当前记录id
	 * @param req 用户请求
	 * @return 
	 * @author caiyinli 13277030520@qq.com
	 * @date 2016年1月21日
	 * @see 
	 */
	@RequestMapping(value="updateDict" , method = RequestMethod.POST)
	@ResponseBody
   public RequestJson updateDict(String dictVos,String descript,String type,String dictid,HttpServletRequest req) {
        RequestJson result = new RequestJson();
        JSONArray jsonArray = JSONObject.parseArray(dictVos);
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

        try {
            if(!StringUtil.isEmptyString(dictid)) {
                Dict di = dictService.selectByPrimaryKey(dictid);
                dictService.deleteByType(di.getType());  
            }
            if(jsonArray != null && jsonArray.size() >0){
                for(int i = 0;i<jsonArray.size();i++){
                	JSONObject object = jsonArray.getJSONObject(i);
                	
                     Dict dict = new Dict();
                     dict.setId(UniqueNumberUtils.get18UniqueNumber());
                     dict.setDescription(descript);
                     dict.setType(type);
                     dict.setLabel(object.getString("label"));
                     dict.setSort(Integer.valueOf(object.getString("sort")));
                     dict.setValue(Integer.valueOf(object.getString("value")));
                     
                     dictService.insert(dict);
                     LogUtils.insertLog("用户新增数据字典", user.getId(), req);  
                }
            }
            
            //清除缓存
            CacheUtils.remove(CacheConstants.SYS_DICT + type);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
          
        return result;
         
   }

   /**
 * @Description 返回字典新增或编辑页面<br>
 * 
 * @param model
 * @param id 主键id
 * @return  返回新增或编辑页面
 * @author caiyinli 13277030520@qq.com
 * @date 2016年1月25日
 * @see 
 */
@RequestMapping(value = "selectById", method = RequestMethod.GET)
   public String selectById(Model model, String id) {
       try {
           if (String.valueOf(NEW_ID).equals(id)) {
               model.addAttribute("type", Constants.MENU_STATE_ENABLED);
               List<DictVo> dictVos = new ArrayList<DictVo>();
               DictVo dictVo = new DictVo();
               dictVo.setLabel(null);
               dictVo.setValue(null);
               dictVo.setSort(null);
               dictVos.add(dictVo);
               model.addAttribute("dictVos",dictVos);
               model.addAttribute("dictVosSize",1);
           } else {
        	   Dict dict = dictService.selectByPrimaryKey(id);
        	   List<DictVo> dictVos = dict.getDictVoList();
        	   dict.setDictVoList(dictVos);
               model.addAttribute("descript", dict.getDescription());
               model.addAttribute("dictType", dict.getType());
               model.addAttribute("dictId", dict.getId());
               model.addAttribute("dictVos",dictVos);
               model.addAttribute("dictVosSize",dictVos.size());
               model.addAttribute("type", Constants.MENU_STATE_DISABLED);
           }
           
       } catch (Exception e) {
       }
       return "system/dict/dictEdit";
   }
    

	/**
	 * @Description 批量删除数据字典<br>
	 * 
	 * @param dicId 删除数据字典id字符串
	 * @param req 用户请求
	 * @return 
	 * @author caiyinli 13277030520@qq.com
	 * @date 2016年2月19日
	 * @see 
	 */
	@RequestMapping(value="deleteByPrimaryKey" , method = RequestMethod.POST)
	@ResponseBody
	public RequestJson deleteByPrimaryKey(String dicId, HttpServletRequest req) {
	    RequestJson result = new RequestJson();
	    User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

	    try {
	        String ids[] = dicId.split("\\,");
	        for(int i = 0; i < ids.length ; i++){
	            Dict dict = dictService.selectByPrimaryKey(ids[i]);
	            if(dict != null){
	                dictService.deleteByType(dict.getType());
	                LogUtils.insertLog("用户删除数据字典信息", user.getId(), req);
	                //清除缓存
	                CacheUtils.remove(CacheConstants.SYS_DICT + dict.getType());
	            }
	        }
	        result.setSuccess(true);
	    } catch (Exception e) {
	        result.setSuccess(false);
	        result.setMsg("操作失败");
	    }
	    return result;
	}
	
    /** 
     * 从缓存中获取数据字典
     * @param type  数据类型
     * @param req  请求
     * @return RequestJson  返回执行结果
     */
	@RequestMapping(value="getDictFromCache" , method = RequestMethod.GET)
	@ResponseBody
    public List<Dict> getDictFromCache(String type) {
        return dictService.getDictFromCache(type);
    }
}
